package com.hexiang.servlet;

import com.hexiang.listener.MyAsyncListener;
import com.hexiang.task.AsyncTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.AsyncContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ThreadPoolExecutor;

@WebServlet(urlPatterns = "/blockingAsyncServlet", asyncSupported = true)
@Slf4j
public class BlockingAsyncServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        long startTime = System.currentTimeMillis();
        log.info("AsyncServletStart");

        httpServletRequest.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);

        String time = httpServletRequest.getParameter("time");
        int secs = StringUtils.isNotBlank(time) ? Integer.parseInt(time) : 2000;

        AsyncContext asyncCtx = httpServletRequest.startAsync();
        asyncCtx.addListener(new MyAsyncListener());
        //异步servlet的超时时间,异步Servlet有对应的超时时间，如果在指定的时间内没有执行完操作，response依然会走原来Servlet的结束逻辑，后续的异步操作执行完再写回的时候，可能会遇到异常。
        asyncCtx.setTimeout(900000000);

        ThreadPoolExecutor executor = (ThreadPoolExecutor) httpServletRequest
                .getServletContext().getAttribute("executor");

        executor.execute(new AsyncTask(asyncCtx, secs));
        long endTime = System.currentTimeMillis();
        log.info("AsyncServletEnd,time cost {} ms.", endTime - startTime);
    }
}